/**
 * Copyright (C) 2010-2016 eBusiness Information, Excilys Group
 * <p>
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
 * use this file except in compliance with the License. You may obtain a copy of
 * the License at
 * <p>
 * http://www.apache.org/licenses/LICENSE-2.0
 * <p>
 * Unless required by applicable law or agreed To in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 */

package org.ohosannotations.api.sharedpreferences;

import ohos.data.preferences.Preferences;

/**
 * 编辑助手
 *
 * @param <T> 泛型
 * @since 2021-07-19
 */
public abstract class EditorHelper<T extends EditorHelper<T>> {
    private final Preferences editor;

    /**
     * 构造参数
     *
     * @param sharedPreferences 预设参数
     */
    public EditorHelper(Preferences sharedPreferences) {
        editor = sharedPreferences;
    }

    /**
     * 获取编辑器
     *
     * @return Preferences 预设参数
     */
    protected Preferences getEditor() {
        return editor;
    }

    /**
     * 清空
     *
     * @return T 泛型
     */
    public final T clear() {
        editor.clear();
        return cast();
    }

    /**
     * 申请
     */
    public final void apply() {
        SharedPreferencesCompat.apply(editor);
    }

    /**
     * 整数字段
     *
     * @param key 键
     * @return IntPrefEditorField 整数编辑字段
     */
    protected IntPrefEditorField<T> intField(String key) {
        return new IntPrefEditorField<>(cast(), key);
    }

    /**
     * 字符串字段
     *
     * @param key 键
     * @return StringPrefEditorField字符串编辑字段
     */
    protected StringPrefEditorField<T> stringField(String key) {
        return new StringPrefEditorField<>(cast(), key);
    }

    /**
     * 字符串设置字段
     *
     * @param key 键
     * @return StringSetPrefEditorField字符串设置编辑器字段
     */
    protected StringSetPrefEditorField<T> stringSetField(String key) {
        return new StringSetPrefEditorField<>(cast(), key);
    }

    /**
     * 布尔字段
     *
     * @param key 键
     * @return BooleanPrefEditorField布尔编辑字段
     */
    protected BooleanPrefEditorField<T> booleanField(String key) {
        return new BooleanPrefEditorField<>(cast(), key);
    }

    /**
     * 浮点字段
     *
     * @param key 键
     * @return FloatPrefEditorField 浮点编辑字段
     */
    protected FloatPrefEditorField<T> floatField(String key) {
        return new FloatPrefEditorField<>(cast(), key);
    }

    /**
     * long字段
     *
     * @param key 键
     * @return LongPrefEditorField long类型编辑字段
     */
    protected LongPrefEditorField<T> longField(String key) {
        return new LongPrefEditorField<>(cast(), key);
    }

    @SuppressWarnings("unchecked")
    private T cast() {
        return (T) this;
    }
}
